package org.grey.edz;

import org.grey.edz.converter.i.IDZipConverter;
import org.grey.edz.ex.EDZException;
import org.grey.edz.payload.EDZPayload;
import org.grey.edz.rule.parser.i.IDZipRuleParser;


import java.lang.reflect.InvocationTargetException;

/**
 * @program: easy-data-zipper
 * @ClassName EasyDZipperProcessor
 * @description: 处理器
 * todo 负责组件调度、任务调度
 * todo 内部组件支持定制，处理器本身不应该支持定制，IDZipperProcessor接口考虑移除
 * todo 如果支持注入，能不能更好的适配容器框架，那就需要再Processor层支持定制组件内部组件，可以预留一个口子，注入能更加规范的给业务实现payload的属性。 结合容器框架姿势大致为构建一个ProcessorBean 注入到业务层后去创建EDZ实例。
 * todo 线程不安全 多个方法间的共享变量，一个锁锁不住，之后优化
 * @author: Grey
 * @create: 2024-01-09 17:20
 */
public class EasyDZipperProcessor extends EDZPayload implements IDZipperProcessor, IDZipperProcessorConfiguration{

    //
    private ConverterEnum defConverterEnum;

    private IDZipRuleParser ruleParser;
    private IDZipConverter converter;

    public EasyDZipperProcessor() {
    }

    public EasyDZipperProcessor(IDZipRuleParser ruleParser, IDZipConverter converter) {
        this.converter = converter;
        this.ruleParser = ruleParser;
    }


    @Override
    public ConverterEnum defaultConverterEnum() {
        return defConverterEnum;
    }

    @Override
    public boolean predicate(Object source) {
        //切换源
        this.setSource(source);
        try {
            return ruleParser.predicate(this);
        } catch (NoSuchMethodException e) {
            throw new EDZException("反射异常:NoSuchMethodException找不到目标方法");
        } catch (InvocationTargetException e) {
            throw new EDZException("反射异常:InvocationTargetException");
        } catch (IllegalAccessException e) {
            throw new EDZException("反射异常:IllegalAccessException无访问权限");
        }
    }

    @Override
    public Object doZipper(Object source, ConverterEnum converterEnum) {
        super.setSource(source);
        try {
            converter.convert(this);
        } catch (NoSuchMethodException e) {
            throw new EDZException("反射异常:NoSuchMethodException找不到目标方法");
        } catch (InvocationTargetException e) {
            throw new EDZException("反射异常:InvocationTargetException");
        } catch (IllegalAccessException e) {
            throw new EDZException("反射异常:IllegalAccessException无访问权限");
        }
        return super.getTarget();
    }
}
